package com.zzzyh.forumsystemclient.cotroller;

import com.alibaba.fastjson.JSON;
import com.zzzyh.forumsystemclient.common.AppResult;
import com.zzzyh.forumsystemclient.model.ArticleReply;
import com.zzzyh.forumsystemclient.model.LoginUser;
import com.zzzyh.forumsystemclient.model.User;
import com.zzzyh.forumsystemclient.services.IArticleReplyService;
import com.zzzyh.forumsystemclient.services.IUserService;
import com.zzzyh.forumsystemclient.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 郑雨杭
 * @create 2025/6/5 - 15:26
 */
@Slf4j
@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private IArticleReplyService articleReplyService;
    @Autowired
    private IUserService userService;
    @RequestMapping("/addComment")
    public AppResult<Long> addComment(@RequestHeader("Authorization") String token,@RequestBody ArticleReply articleReply){
        String userString = JwtUtils.getSubjectFromToken(token);
        User user = JSON.parseObject(userString, LoginUser.class).getUser();
        articleReply.setPostUserId(user.getId());
        log.info("添加评论：{}", articleReply);
        articleReplyService.addArticleReply(articleReply);
        return AppResult.success(articleReply.getId());
    }

    @RequestMapping("/getCommentsByArticleId")
    public AppResult<List<ArticleReply>> getCommentsByArticleId(@RequestParam("articleId") Long articleId){
        List<ArticleReply> commentsByArticle = articleReplyService.getCommentsByArticleId(articleId);
        for (ArticleReply comment : commentsByArticle) {
            User postUser = userService.selectUserByUserId(comment.getPostUserId());
            comment.setPostUser(postUser);
        }
        return AppResult.success(commentsByArticle);
    }
}
